package com.org.khtn.gui;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;
import java.util.Vector;

import javax.swing.JTable;

import com.org.khtn.data.Manager;

public class TableDesignListener implements PropertyChangeListener {
	public JTable table;
	public Map<String, String> tableDefines;
	public Manager manager;
	public String databaseName;
	public String tableName;

	public TableDesignListener(JTable tb, Manager mg, String dbName, String tbName) {
		table = tb;
		manager = mg;
		tableDefines = manager.getTableDefines(dbName, tbName);
		databaseName = dbName;
		tableName = tbName;
	}

	@Override
	public void propertyChange(PropertyChangeEvent e) {
		// System.out.println(e.getPropertyName());
		if ("tableCellEditor".equals(e.getPropertyName())
				&& table.getSelectedColumn() == 1) {
			if (table.isEditing() == false) {
				Vector colInTable = new Vector();
				for (int i = 0; i < table.getRowCount(); i++) {
					colInTable.add(table.getValueAt(i, 1));
				}
				Vector colInDatabase = new Vector();
				for (Map.Entry<String, String> df : tableDefines.entrySet()) {
					colInDatabase.add(df.getKey());
				}
				for (int i = colInDatabase.size() - 1; i > 0; i--) {
					if (colInTable.contains(colInDatabase.elementAt(i))) {
						colInTable.remove(colInDatabase.elementAt(i));
						colInDatabase.removeElementAt(i);
					}
				}
				
				if (colInDatabase.size() == 1 && colInTable.size() == 1) {
					manager.editTableFieldName(databaseName, tableName, (String)colInDatabase.elementAt(0), (String)colInTable.elementAt(0));
				}
				
				System.out.println(table.getValueAt(table.getSelectedRow(),
						table.getSelectedColumn()));
			}
		}
	}
}
